import Taro from "@tarojs/taro";
import {submit, update} from "@/_framework/services/Data";
import {getStorageSync, getLocation, navigateTo, getWxCode, getFuzzyLocation,} from "@/_framework/services/Taro";
import {postAuth} from "@/_framework/services/Request";
import {getTenantId} from "@/_framework/Config";


export async function doLogin(params) {
    const {referrer = "", source = "", force = false} = params || {};
    if (getStorageSync("access_token") && !force) {
        //存在 token，且非强制登录，则不处理
        return;
    }
    await doPostAuth({referrer, source});
    doLocation();
}

export async function doPostAuth({referrer = "", source = ""}) {
    const {access_token, refresh_token, expires_in} = await postAuth({
        code: await getWxCode(), referrer, source, tenantId: getTenantId(),
        grant_type: 'open_id',
    });
    Taro.setStorageSync("access_token", access_token);
    Taro.setStorageSync("refresh_token", refresh_token);
    Taro.setStorageSync("expires_in", expires_in);
}


async function doLocation() {
    const {longitude, latitude} = await getFuzzyLocation();
    await submit("turing/userInfo/updateLocation", {longitude, latitude})

}

